<?php
declare (strict_types = 1);

namespace app\admin\model;

use think\Exception;
use think\facade\Config;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class goods extends Model
{
    //
    use SoftDelete;
    protected $deleteTime = "del_time";
    protected $pk = 'goods_id';
    protected $error;
    public function getError()
    {
        return $this->error;
    }

    protected $autoWriteTimestamp = true;
    protected $createTime = 'add_time';
    protected $updateTime = 'last_update';
    //模糊搜索
    public function searchGoodsNameAttr($query,$value,$data){
        if (''!==$value){
            $query->whereLike('goods_name','%'.$value.'%');
        }
    }

    public function searchIfShowAttr($query,$value,$data){
        if (is_array($value) || (is_scalar($value) && strpos('#'.$value,','))){
            $query->whereIn('ecm_goods.if_show',$value);
        }

        if (is_scalar($value) && false === strpos($value,',') && intval($value) < 2){
            $query->where('ecm_goods.if_show',intval($value));
        }
    }
    public function setPvaluesAttr($value){
        if (is_array($value)){
            return implode(',',$value);
        }
        return $value;
    }
    public function searchRecommendedAttr($query,$value,$data){
        //针对复选框形式
        if (is_array($value) || (is_scalar($value) && strpos('#'.$value,','))){
            $query->whereIn('ecm_goods.recommended',$value);
        }
        //针对单选框
        if (is_scalar($value) && false === strpos($value,',') && intval($value) < 2){
            $query->where('ecm_goods.recommended',$value);
        }
    }

    public function searchCidAttr($query,$value,$data){
        if (isset($value) && !empty($value)){
            $query->where('c.cate_id',$data['cid']);
        }
    }

    public function searchAddTimesAttr($query,$value){
        if (!empty($value)){
            $query->whereTime('add_time','>=',$value);
        }
    }
    public function searchAddTimessAttr($query,$value){
        if (!empty($value)){
            $query->whereTime('add_time','<=',$value);
        }
    }

    public function searchAddTimeAttr($query,$value){
        if (!empty($value) && is_array($value) && 2 === count($value)){
            $query->whereTime('ecm_goods.add_time',$value[0],$value[1]);
        }
    }

    public function searchPricesAttr($query,$value){
        if (!empty($value)){
            $query->where('price','>=',$value);
        }
    }
    public function searchPricessAttr($query,$value){
        if (!empty($value)){
            $query->where('price','<=',$value);
        }
    }
//    public function searchPricesssAttr($query,$value){
//        if (!empty($value) && is_array($value) && 2 === count($value)){
//            $query->where('ecm_goods.price',$value[0],$value[1]);
//        }
//    }
    public static function checkBrandId($brand_id){
        if (is_array($brand_id) && !empty($brand_id)){
            return self::field('goods_id')->whereIn('brand',$brand_id)->find();
        }
        if (!empty($brand_id) && is_string($brand_id) && false === strpos($brand_id,',')){
            return self::getByBrand($brand_id);
        }
        if (!empty($brand_id) && is_string($brand_id) && false !== strpos($brand_id,',')){
            $brand_id = explode(',',$brand_id);
            return self::field('goods_id')->whereIn('brand',$brand_id)->find();
        }

        return false;
    }
    public function searchSortAttr($query,$value){
        if (isset($vlaue) && 'desc' == $value){
            $query->order('add_time','desc');
        }elseif (isset($value) && 'asc' == $value){
            $query->order('add_time','asc');
        }else{
            $query->order('goods_id','desc');
        }
    }

    public function searchPageAttr($query,$value){}

    //时间转换
    public function getAddTimeAttr($value){
        return date('Y-m-d H:i:s',$value);
    }
    public function getRecommendedAttr($value)
    {
        return $value?'dui.jpg':'cuo.jpg';
    }
    public function getRecomAttr($value)
    {
        return $value?'dui.jpg':'cuo.jpg';
    }
    public function getIfShowAttr($value)
    {
        return $value?'dui.jpg':'cuo.jpg';
    }
//    public function getDefaultImageAttr($value)
//    {
//        return $value==''?'default.png':$value;
//    }
    //构造新字段
//   public function getGoodsTitleAttr($value, $data)
//    {
//       if (mb_strlen($data['goods_name'], 'utf-8') > 6) {
//           return '[' . $data['cate_id'] . ']' . mb_substr($data['goods_name'], 0, 6, 'utf-8') . '...';
//      }
//
//      return '[' . $data['cate_id'] . ']' . $data['goods_name'];
//  }
    public static function getGoodsList($data=[],$query=[],$page=false,$res=false){
        $field=[
            'g.goods_id','brand','goods_name','g.cate_id','price','g.if_show','last_update','add_time','default_image','g.recommended','recom',
            'c.cate_name','parent_id','c.sort_order','c.cate_id','c.parent_id',
            'b.brand_id','b.brand_name',

        ];
        if ($res){
            $asd = self::onlyTrashed()->alias('g');
        }else{
            $asd = self::alias('g');
        }

            $model=$asd->field($field)
            ->join(['ecm_gcategory'=>'c'],'g.cate_id=c.cate_id','LEFT')
            ->join(['ecm_brand'=>'b'],'g.brand=b.brand_id','LEFT')
            ->order('g.goods_id')
            ->withSearch(array_keys($data),$data);

        $list_rows = Config::has('view.list_rows')?Config::get('view.list_rows'):15;

        if ($page){
            $result = $model->select();
        }else{
            $result = $model->paginate([
                'list_rows' => $list_rows,
                'query'     => $query,
            ]);
        }
        return $result;
    }
    public function add(array $data,array $allowField = [],bool $replace = false)  //商品添加
    {
        try {
            if (empty($data)) {
                $this->error = '数据不能为空!';
            }
            if (!empty($allowField)) {
                $this->allowField($allowField);
            }
            $this->replace($replace)->save($data);
            $id = $this->toArray();
            return $id[$this->pk];
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }
    public function upt($data, $where = [],$allowField = []){
        try{
            if (empty($data)){
                $this->error = "修改数据不能为空";
                return ;
            }

            if (!empty($allowField)) {
                $this->allowField($allowField);
            }
            if (!empty($where)){
                $this->setUpdateWhere($where);

                if (isset($data[$this->pk]))   unset($data[$this->pk]);
            }

            return $this->exists(true)->save($data);
        }catch (Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
}
